package cn.starrysky108.simpleerp.core.security;

import cn.starrysky108.simpleerp.core.util.JwtUtil;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt授权过滤器
 *
 * @author Carl Lee
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final UserDetailsService userDetailsService;

    public JwtAuthenticationFilter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain) throws ServletException, IOException {
        String jwt = JwtUtil.getHeaderToken(request);
        if (!StringUtils.hasText(jwt) || jwt.length() < 10) {
            doFilterNestedErrorDispatch(request, response, chain);
            return;
        }
        // 验证token
        String username = JwtUtil.verify(jwt, response);
        if (!StringUtils.hasText(username)) {
            //非法token或者token过期直接返回，不进入过滤器链
            return;
        }
        UserDetailsEntity userDetails = (UserDetailsEntity) userDetailsService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token);
        doFilterNestedErrorDispatch(request, response, chain);
    }
}
